package com.xuanwei.core.aspect;

import com.xuanwei.core.annos.Single;
import com.xuanwei.core.entity.bo.WxUserDetail;
import com.xuanwei.core.exception.XwException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @Author jiangyong
 * @Description TODO
 * @Date 2019/8/27 10:19
 **/
@Aspect
@Component
public class SingleHandler {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Pointcut("@annotation(com.xuanwei.core.annos.Single)")
    public void pointcut() {
    }

    @Before(value = "pointcut()&&@annotation(single)", argNames = "joinPoint,single")
    public void handler(JoinPoint joinPoint, Single single) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            throw new XwException("未登录");
        }
        WxUserDetail principal = (WxUserDetail) authentication.getPrincipal();
        Integer userId = Integer.parseInt(principal.getUsername());
        String method = joinPoint.getSignature().getName();
        String key = userId + "-" + method;
        Object object = redisTemplate.opsForValue().get(key);
        if (object == null) {
            redisTemplate.opsForValue().set(key, 1, single.second(), TimeUnit.SECONDS);
        } else {
            throw new XwException("系统繁忙,请稍后再试");
        }

    }
}
